<template>
  <div class="bg-gray-800 rounded-lg p-4">
    <div class="flex justify-between items-center mb-4">
      <h3 class="text-lg font-medium">API 密钥管理</h3>
      <button 
        @click="refreshApiKeys" 
        class="p-1 rounded-full hover:bg-gray-700 text-gray-400 hover:text-white"
        title="刷新API密钥列表"
        :disabled="isLoading"
      >
        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
        </svg>
      </button>
    </div>
    
    <!-- 加载状态 -->
    <div v-if="isLoading" class="flex justify-center items-center py-8">
      <div class="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-[#8153ff]"></div>
      <span class="ml-2 text-gray-400">加载中...</span>
    </div>
    
    <!-- 空状态显示 -->
    <div v-else-if="localApiKeys.length === 0" class="bg-gray-700 rounded-lg p-6 text-center mb-6">
      <svg xmlns="http://www.w3.org/2000/svg" class="h-12 w-12 mx-auto text-gray-500 mb-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 11c0 3.517-1.009 6.799-2.753 9.571m-3.44-2.04l.054-.09A13.916 13.916 0 008 11a4 4 0 118 0c0 1.017-.07 2.019-.203 3m-2.118 6.844A21.88 21.88 0 0015.171 17m3.839 1.132c.645-2.266.99-4.659.99-7.132A8 8 0 008 4.07M3 15.364c.64-1.319 1-2.8 1-4.364 0-1.457.39-2.823 1.07-4" />
      </svg>
      <p class="text-gray-400 mb-4">尚未添加任何API密钥</p>
      <p class="text-sm text-gray-500">请使用下方的按钮添加API密钥</p>
    </div>
    
    <div v-else class="mb-6">
      <div 
        v-for="(apiKey, index) in localApiKeys" 
        :key="index"
        class="bg-gray-700 rounded-lg p-4 mb-3"
      >
        <div class="flex justify-between items-center mb-2">
          <h4 class="font-medium">{{ apiKey.provider }}</h4>
          <div class="flex space-x-2">
            <button 
              @click="toggleEdit(index)"
              class="p-1 text-gray-400 hover:text-white"
              :title="apiKey.editing ? '保存' : '编辑'"
            >
              <svg v-if="!apiKey.editing" xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
              </svg>
              <svg v-else xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
              </svg>
            </button>
            
            <!-- 测试API按钮 -->
            <button 
              @click="testApiConnection(index)"
              class="p-1 text-gray-400 hover:text-blue-500"
              title="测试API连接"
              :disabled="apiKey.testing"
            >
              <svg v-if="!apiKey.testing" xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z" />
              </svg>
              <div v-else class="animate-spin h-5 w-5 border-2 border-blue-500 rounded-full border-t-transparent"></div>
            </button>
            
            <button 
              @click="deleteApiKey(index)"
              class="p-1 text-gray-400 hover:text-red-500"
              title="删除"
            >
              <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
              </svg>
            </button>
          </div>
        </div>
        
        <div class="space-y-3">
          <div>
            <label class="block text-sm text-gray-400 mb-1">API 密钥</label>
            <div v-if="!apiKey.editing" class="flex bg-gray-800 p-2 rounded">
              <div class="flex-1 overflow-hidden">
                <span v-if="apiKey.showKey">{{ apiKey.key }}</span>
                <span v-else>{{ maskApiKey(apiKey.key) }}</span>
              </div>
              <button 
                @click="toggleShowKey(index)" 
                class="text-gray-400 hover:text-white ml-2"
                :title="apiKey.showKey ? '隐藏' : '显示'"
              >
                <svg v-if="apiKey.showKey" xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21" />
                </svg>
                <svg v-else xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                </svg>
              </button>
            </div>
            <input 
              v-else
              v-model="apiKey.key"
              type="text" 
              class="w-full bg-gray-800 border border-gray-600 rounded px-3 py-2 focus:outline-none focus:ring-2 focus:ring-[#8153ff] focus:border-transparent"
            />
          </div>
          
          <!-- 显示测试结果 -->
          <div v-if="apiKey.testResult" class="mt-2 p-2 rounded-md" :class="apiKey.testSuccess ? 'bg-green-900 bg-opacity-20 text-green-400' : 'bg-red-900 bg-opacity-20 text-red-400'">
            <div class="flex items-start">
              <div v-if="apiKey.testSuccess" class="mr-2 flex-shrink-0 mt-0.5">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
                </svg>
              </div>
              <div v-else class="mr-2 flex-shrink-0 mt-0.5">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                </svg>
              </div>
              <div class="text-sm">{{ apiKey.testResult }}</div>
            </div>
          </div>
          
          <div>
            <label class="block text-sm text-gray-400 mb-1">API 地址</label>
            <div v-if="!apiKey.editing" class="bg-gray-800 p-2 rounded overflow-hidden text-ellipsis">
              {{ apiKey.endpoint }}
            </div>
            <input 
              v-else
              v-model="apiKey.endpoint"
              type="text" 
              class="w-full bg-gray-800 border border-gray-600 rounded px-3 py-2 focus:outline-none focus:ring-2 focus:ring-[#8153ff] focus:border-transparent"
            />
          </div>
          
          <!-- 显示模型名称（如果有） -->
          <div v-if="apiKey.modelName">
            <label class="block text-sm text-gray-400 mb-1">模型名称</label>
            <div v-if="!apiKey.editing" class="bg-gray-800 p-2 rounded overflow-hidden text-ellipsis">
              {{ apiKey.modelName }}
            </div>
            <input 
              v-else
              v-model="apiKey.modelName"
              type="text" 
              class="w-full bg-gray-800 border border-gray-600 rounded px-3 py-2 focus:outline-none focus:ring-2 focus:ring-[#8153ff] focus:border-transparent"
            />
          </div>
        </div>
      </div>
    </div>
    
    <div class="flex space-x-2">
      <button 
        @click="addNewApiKey"
        class="flex-1 py-2 text-center bg-gray-700 hover:bg-gray-600 rounded-lg text-white transition-colors flex items-center justify-center"
      >
        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
        </svg>
        添加预设密钥
      </button>
      
      <button 
        @click="showCustomModal = true"
        class="flex-1 py-2 text-center bg-gradient-to-r from-[#8153ff] to-[#93dc24] rounded-lg text-white transition-colors flex items-center justify-center"
      >
        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
        </svg>
        添加自定义密钥
      </button>
    </div>
    
    <!-- 添加自定义密钥模态框 -->
    <div 
      v-if="showCustomModal" 
      class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50"
    >
      <div class="bg-gray-800 rounded-lg p-6 w-96 max-w-full">
        <div class="flex justify-between items-center mb-4">
          <h3 class="text-lg font-medium">添加自定义密钥</h3>
          <button @click="showCustomModal = false" class="text-gray-400 hover:text-white">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>
        
        <div class="space-y-4">
          <div>
            <label class="block text-sm text-gray-400 mb-1">API 密钥</label>
            <input 
              v-model="customApiKey.key"
              type="text" 
              class="w-full bg-gray-700 border border-gray-600 rounded px-3 py-2 focus:outline-none focus:ring-2 focus:ring-[#8153ff] focus:border-transparent"
              placeholder="sk-xxxxxxxx"
            />
          </div>
          
          <div>
            <label class="block text-sm text-gray-400 mb-1">API 地址</label>
            <input 
              v-model="customApiKey.endpoint"
              type="text" 
              class="w-full bg-gray-700 border border-gray-600 rounded px-3 py-2 focus:outline-none focus:ring-2 focus:ring-[#8153ff] focus:border-transparent"
              placeholder="https://example.com/api/"
            />
            
            <div class="mt-1 text-xs text-gray-400">
              <div>* 地址以 / 结尾: 忽略v1版本路径</div>
              <div>* 地址以 # 结尾: 强制使用输入的地址</div>
            </div>
          </div>
          
          <div>
            <label class="block text-sm text-gray-400 mb-1">模型名称</label>
            <input 
              v-model="customApiKey.modelName"
              type="text" 
              class="w-full bg-gray-700 border border-gray-600 rounded px-3 py-2 focus:outline-none focus:ring-2 focus:ring-[#8153ff] focus:border-transparent"
              placeholder="填写要使用的模型名称"
            />
          </div>
          
          <div>
            <label class="block text-sm text-gray-400 mb-1">模型ID</label>
            <input 
              v-model="customApiKey.provider"
              type="text" 
              class="w-full bg-gray-700 border border-gray-600 rounded px-3 py-2 focus:outline-none focus:ring-2 focus:ring-[#8153ff] focus:border-transparent"
              placeholder="填写对应服务提供商的模型ID"
            />
          </div>
        </div>
        
        <div class="mt-6 flex space-x-2">
          <button 
            @click="showCustomModal = false"
            class="flex-1 py-2 bg-gray-700 hover:bg-gray-600 rounded-lg"
            :disabled="isSubmitting"
          >
            取消
          </button>
          <button 
            @click="addCustomApiKey"
            class="flex-1 py-2 bg-gradient-to-r from-[#8153ff] to-[#93dc24] text-white rounded-lg hover:opacity-90 flex items-center justify-center"
            :disabled="!isValidCustomKey || isSubmitting"
          >
            <span v-if="!isSubmitting">添加</span>
            <div v-else class="flex items-center">
              <div class="animate-spin h-4 w-4 border-2 border-white rounded-full border-t-transparent mr-2"></div>
              提交中...
            </div>
          </button>
        </div>
      </div>
    </div>
    
    <!-- 错误提示组件 -->
    <div v-if="errorMessage" class="mt-4 bg-red-500 bg-opacity-20 border border-red-500 rounded-md p-3 flex items-start">
      <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-red-500 mr-2 flex-shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
      </svg>
      <div class="text-sm text-red-100">{{ errorMessage }}</div>
    </div>
    
    <!-- 成功提示组件 -->
    <div v-if="successMessage" class="mt-4 bg-green-500 bg-opacity-20 border border-green-500 rounded-md p-3 flex items-start">
      <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-green-500 mr-2 flex-shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
      </svg>
      <div class="text-sm text-green-100">{{ successMessage }}</div>
    </div>
  </div>
</template>

<script setup>
import { ref, defineProps, defineEmits, watch, computed, onMounted } from 'vue';

const props = defineProps({
  apiKeys: {
    type: Array,
    default: () => []
  }
});

const emit = defineEmits(['update:apiKeys']);

// 本地API密钥列表，用于内部操作
const localApiKeys = ref([]);
const isLoading = ref(false);
const hasLoadedFromBackend = ref(false); // 标记是否已从后端加载过数据
const isSubmitting = ref(false); // 添加自定义API密钥时的提交状态

// 错误和成功消息
const errorMessage = ref('');
const successMessage = ref('');

// API基础URL
const API_BASE_URL = 'http://localhost:3000/api';

// 组件挂载时获取API密钥
onMounted(async () => {
  console.log('组件挂载，强制刷新API密钥列表');
  // 强制从后端加载数据，忽略hasLoadedFromBackend标志
  await fetchApiKeys(true);
});

// 从后端获取API密钥列表
const fetchApiKeys = async (forceRefresh = false) => {
  // 如果正在加载，等待加载完成
  if (isLoading.value) return;
  
  // 如果已加载过且不是强制刷新，则不重复加载
  if (hasLoadedFromBackend.value && !forceRefresh) return;
  
  try {
    console.log('开始从后端获取API密钥列表...');
    isLoading.value = true;
    
    // 添加随机参数和缓存控制头部，防止浏览器缓存
    const timestamp = new Date().getTime();
    const response = await fetch(`${API_BASE_URL}/api-keys?_=${timestamp}`, {
      headers: {
        'Cache-Control': 'no-cache, no-store, must-revalidate',
        'Pragma': 'no-cache',
        'Expires': '0'
      }
    });
    
    const data = await response.json(); // 只消费一次响应体
    
    // 检查响应状态
    if (!response.ok) {
      throw new Error(data.error || '获取API密钥列表失败');
    }
    
    console.log('从后端获取的API密钥:', data);
    
    // 转换后端数据格式为前端需要的格式
    const formattedKeys = Array.isArray(data) ? data.map(key => ({
      id: key.id,
      provider: key.provider,
      key: key.key,
      endpoint: key.endpoint,
      showKey: false,
      editing: false,
      modelName: key.model_name || key.modelName || '' // 兼容不同字段名
    })) : [];
    
    console.log('格式化后的API密钥:', formattedKeys);
    
    // 更新本地数据
    localApiKeys.value = formattedKeys;
    // 通知父组件更新
    emitUpdate();
    
    // 标记已从后端加载过数据
    hasLoadedFromBackend.value = true;
    
    if (formattedKeys.length > 0) {
      showSuccess(`成功加载 ${formattedKeys.length} 个API密钥`);
    } else {
      console.log('后端没有返回API密钥数据或数据为空数组');
    }
  } catch (error) {
    console.error('获取API密钥列表失败:', error);
    showError(`获取API密钥失败: ${error.message}`);
    // 出错时也标记为已加载，避免无限重试
    hasLoadedFromBackend.value = true;
  } finally {
    isLoading.value = false;
  }
};

// 显示消息的辅助函数
const showError = (message) => {
  errorMessage.value = message;
  // 5秒后自动清除错误消息
  setTimeout(() => {
    errorMessage.value = '';
  }, 5000);
};

const showSuccess = (message) => {
  successMessage.value = message;
  // 3秒后自动清除成功消息
  setTimeout(() => {
    successMessage.value = '';
  }, 3000);
};

// 监听props.apiKeys变化，更新本地数据
watch(() => props.apiKeys, (newValue) => {
  console.log('props.apiKeys变化:', newValue);
  
  // 如果props.apiKeys有值且不为空数组，使用它
  if (newValue && newValue.length > 0) {
    console.log('使用props中的API密钥数据');
    localApiKeys.value = JSON.parse(JSON.stringify(newValue)); // 深拷贝
    hasLoadedFromBackend.value = true; // 标记已有数据
  } else if (!hasLoadedFromBackend.value) {
    // 如果props为空且尚未从后端加载数据，则加载数据
    console.log('props为空，从后端加载API密钥数据');
    fetchApiKeys(true); // 添加强制刷新参数
  }
}, { immediate: true, deep: true }); // 添加deep:true以捕获数组内部变化

// 掩码显示API密钥
const maskApiKey = (key) => {
  if (!key) return '';
  const prefix = key.substring(0, 3);
  const suffix = key.substring(key.length - 4);
  return `${prefix}...${suffix}`;
};

// 切换显示/隐藏API密钥
const toggleShowKey = (index) => {
  localApiKeys.value[index].showKey = !localApiKeys.value[index].showKey;
  emitUpdate();
};

// 切换编辑模式
const toggleEdit = async (index) => {
  if (localApiKeys.value[index].editing) {
    // 尝试保存更改
    try {
      const apiKey = localApiKeys.value[index];
      console.log('正在保存API密钥编辑:', apiKey);
      
      // 验证数据
      if (!apiKey.key || !apiKey.provider || !apiKey.endpoint) {
        showError('API密钥、模型ID和API地址不能为空');
        return;
      }
      
      // 检查是否需要保存到后端
      // 如果id不存在，或者id是字符串且以临时ID前缀开头，则需要保存到后端
      const needsSave = !apiKey.id || 
                        (typeof apiKey.id === 'string' && 
                         (apiKey.id.startsWith('preset-') || apiKey.id.startsWith('custom-')));
      
      console.log('是否需要保存到后端:', needsSave);
      
      // 如果是新添加的且没有后端ID，则保存到后端
      if (needsSave) {
        console.log('尝试保存API密钥到后端...');
        const result = await saveApiKeyToBackend(apiKey);
        console.log('保存到后端结果:', result);
        
        if (!result.success) {
          showError('保存失败: ' + (result.message || '未知错误'));
          return;
        }
        
        // 如果保存成功且返回了ID，使用后端返回的ID
        if (result.id && !result.localOnly) {
          console.log('使用后端返回的ID:', result.id);
          apiKey.id = result.id;
        }
        
        // 显示提示
        if (result.localOnly) {
          showSuccess('密钥已更新并保存到本地存储，但未能保存到服务器');
        } else {
          showSuccess('API密钥已保存到服务器');
        }
      }
      
      // 保存成功，退出编辑模式
      localApiKeys.value[index].editing = false;
      emitUpdate();
      console.log('API密钥编辑保存完成');
    } catch (error) {
      console.error('保存API密钥失败:', error);
      showError(`保存失败: ${error.message}`);
    }
  } else {
    // 进入编辑模式
    console.log('进入API密钥编辑模式:', localApiKeys.value[index]);
    localApiKeys.value[index].editing = true;
    emitUpdate();
  }
};

// 删除API密钥
const deleteApiKey = async (index) => {
  if (confirm('确定要删除这个API密钥吗?')) {
    try {
      const apiKey = localApiKeys.value[index];
      console.log('尝试删除API密钥:', apiKey);
      
      // 检查id类型，确定是后端返回的数字ID还是前端生成的临时字符串ID
      const isBackendId = apiKey.id && (typeof apiKey.id === 'number' || 
                          (typeof apiKey.id === 'string' && 
                           !apiKey.id.startsWith('preset-') && 
                           !apiKey.id.startsWith('custom-')));
      
      console.log('是后端ID?', isBackendId, '类型:', typeof apiKey.id);
      
      // 如果是后端ID，则从后端删除
      if (isBackendId) {
        isLoading.value = true;
        console.log(`删除后端API密钥, ID: ${apiKey.id}`);
        
        const response = await fetch(`${API_BASE_URL}/api-keys/${apiKey.id}`, {
          method: 'DELETE'
        });
        
        if (!response.ok) {
          const errorData = await response.json();
          throw new Error(errorData.error || '删除API密钥失败');
        }
        
        // 从本地数组中立即删除，不等待后端刷新
        localApiKeys.value.splice(index, 1);
        emitUpdate();
        
        showSuccess('API密钥删除成功');
        
        // 延迟一小段时间后再刷新，确保后端操作完成
        setTimeout(async () => {
          // 重置标志，允许重新从后端加载最新数据
          hasLoadedFromBackend.value = false;
          // 从后端重新获取完整的API密钥列表，强制刷新
          await fetchApiKeys(true);
        }, 300);
      } else {
        // 仅从本地数组中移除
        console.log('仅从本地删除API密钥');
        localApiKeys.value.splice(index, 1);
        emitUpdate();
      }
    } catch (error) {
      console.error('删除API密钥失败:', error);
      showError(`删除失败: ${error.message}`);
    } finally {
      isLoading.value = false;
    }
  }
};

// 处理自定义API密钥的地址格式
const processEndpoint = (endpoint) => {
  const trimmedEndpoint = endpoint.trim();
  
  // 如果以/结尾
  if (trimmedEndpoint.endsWith('/')) {
    return {
      processedEndpoint: trimmedEndpoint,
      ignoreV1: true,
      forceUseInput: false
    };
  } 
  // 如果以#结尾
  else if (trimmedEndpoint.endsWith('#')) {
    return {
      processedEndpoint: trimmedEndpoint.slice(0, -1), // 移除#
      ignoreV1: false,
      forceUseInput: true
    };
  } 
  // 正常情况
  else {
    return {
      processedEndpoint: trimmedEndpoint,
      ignoreV1: false,
      forceUseInput: false
    };
  }
};

// 添加新API密钥
const addNewApiKey = async () => {
  // 创建本地API密钥对象
  const newApiKey = {
    id: `preset-${Date.now()}`,
    provider: '新服务提供商',
    key: '',
    endpoint: '',
    showKey: true,
    editing: true
  };
  
  try {
    // 先添加到本地，以便用户编辑
    localApiKeys.value.push(newApiKey);
    emitUpdate();
    
    // 注意：此时不发送到后端，因为用户还没有填写信息
    // 用户会编辑这个新密钥，然后通过toggleEdit保存时将数据发送到后端
  } catch (error) {
    console.error('添加预设API密钥失败:', error);
    showError('添加预设API密钥时出错');
  }
};

// 保存API密钥到后端
const saveApiKeyToBackend = async (apiKey) => {
  try {
    console.log('开始保存API密钥到后端...');
    const response = await fetch(`${API_BASE_URL}/api-keys`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        key: apiKey.key,
        provider: apiKey.provider,
        endpoint: apiKey.endpoint,
        modelName: apiKey.modelName || '' // 添加modelName字段
      })
    });
    
    // 检查响应
    const contentType = response.headers.get("content-type");
    let responseData;
    
    // 尝试解析响应内容
    if (contentType && contentType.includes("application/json")) {
      responseData = await response.json();
    } else {
      const text = await response.text();
      responseData = { error: text || "未知错误" };
    }
    
    if (!response.ok) {
      console.error('保存API密钥到后端失败:', response.status, responseData);
      
      // 服务器错误时，使用localStorage保存
      if (response.status >= 500) {
        console.warn('服务器错误，将使用localStorage保存API密钥');
        return { success: true, message: '服务器错误，已使用本地存储保存API密钥', localOnly: true };
      }
      
      throw new Error(responseData.error || `服务器返回错误状态码: ${response.status}`);
    }
    
    console.log('API密钥保存成功:', responseData);
    return { success: true, id: responseData.id, message: 'API密钥保存成功' };
  } catch (error) {
    console.error('保存API密钥到后端失败:', error);
    
    // 出现任何错误，也尝试使用localStorage
    console.warn('API请求失败，将使用localStorage保存API密钥');
    return { success: true, message: '服务器连接失败，已使用本地存储保存API密钥', localOnly: true };
  }
};

// 添加自定义API密钥
const addCustomApiKey = async () => {
  if (!isValidCustomKey.value) return;
  
  const { processedEndpoint, ignoreV1, forceUseInput } = processEndpoint(customApiKey.value.endpoint);
  
  isSubmitting.value = true;
  
  try {
    // 创建新的API密钥对象
    const newKey = {
      id: `custom-${Date.now()}`, // 生成唯一ID
      provider: customApiKey.value.provider,
      key: customApiKey.value.key,
      endpoint: processedEndpoint,
      modelName: customApiKey.value.modelName || '', // 确保包含modelName
      ignoreV1: ignoreV1,
      forceUseInput: forceUseInput,
      showKey: false,
      editing: false,
      isCustom: true
    };
    
    // 尝试保存到后端
    const result = await saveApiKeyToBackend(newKey);
    
    // 如果后端保存成功且返回了ID，使用后端返回的ID
    if (result.success && result.id && !result.localOnly) {
      newKey.id = result.id;
    }
    
    // 添加到本地数据
    localApiKeys.value.push(newKey);
    
    // 发送更新事件
    emit('update:apiKeys', localApiKeys.value);
    
    // 显示成功消息
    showSuccess(result.localOnly ? 
      '密钥已添加到本地存储，但未能保存到服务器' : 
      '自定义API密钥已添加');
    
    // 重置表单并关闭弹窗
    resetCustomApiKeyForm();
    showCustomModal.value = false;
  } catch (error) {
    // 显示错误消息
    showError(error.message || '无法添加自定义API密钥');
  } finally {
    isSubmitting.value = false;
  }
};

// 重置自定义API密钥表单
const resetCustomApiKeyForm = () => {
  customApiKey.value = {
    provider: '',
    key: '',
    endpoint: '',
    modelName: ''
  };
};

// 向父组件发送更新事件
const emitUpdate = () => {
  emit('update:apiKeys', localApiKeys.value);
};

// 自定义API密钥模态框状态
const showCustomModal = ref(false);

// 自定义API密钥表单
const customApiKey = ref({
  provider: '',
  key: '',
  endpoint: '',
  modelName: ''
});

// 监听模态框显示状态，确保打开时重置表单
watch(showCustomModal, (newValue) => {
  if (newValue) {
    resetCustomApiKeyForm();
  }
});

// 验证自定义API密钥是否有效
const isValidCustomKey = computed(() => {
  return customApiKey.value.key.trim() !== '' && 
         customApiKey.value.endpoint.trim() !== '' && 
         customApiKey.value.provider.trim() !== '';
});

// 刷新API密钥列表
const refreshApiKeys = async () => {
  console.log('手动刷新API密钥列表');
  // 清除本地数据
  localApiKeys.value = [];
  // 重置加载状态
  hasLoadedFromBackend.value = false;
  // 清除消息
  errorMessage.value = '';
  successMessage.value = '';
  // 强制刷新
  await fetchApiKeys(true);
  showSuccess('API密钥列表已刷新');
};

// 测试API连接
const testApiConnection = async (index) => {
  const apiKey = localApiKeys.value[index];
  
  // 设置测试中状态
  apiKey.testing = true;
  apiKey.testResult = undefined;
  apiKey.testSuccess = undefined;
  
  try {
    console.log(`测试API连接: ${apiKey.provider}`);
    
    // 准备测试数据
    const testData = {
      key: apiKey.key,
      provider: apiKey.provider,
      endpoint: apiKey.endpoint,
      modelName: apiKey.modelName || ''
    };
    
    // 发送测试请求到后端
    const response = await fetch(`${API_BASE_URL}/test-api`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(testData)
    });
    
    const result = await response.json();
    
    console.log('API测试结果:', result);
    
    // 更新测试结果
    apiKey.testSuccess = result.success;
    apiKey.testResult = result.message || (result.success ? '测试成功' : '测试失败');
    
    if (result.success) {
      showSuccess(`API "${apiKey.provider}" 测试成功`);
    } else {
      showError(`API测试失败: ${apiKey.testResult}`);
    }
  } catch (error) {
    console.error('API测试失败:', error);
    apiKey.testSuccess = false;
    apiKey.testResult = `测试失败: ${error.message}`;
    showError(`API测试失败: ${error.message}`);
  } finally {
    // 等待一段时间后移除测试中状态，让UI有时间显示动画
    setTimeout(() => {
      apiKey.testing = false;
      emitUpdate();
    }, 500);
  }
};
</script>

<style scoped>
</style> 